LSTM-ED for Anomaly Detection in Time Series Data¶
In [ ]:
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from dataset import *
from plots import *
from metrics import *
from models_funtions import *
# Set style for matplotlib
plt.style.use("Solarize_Light2")
import plotly.io as pio
pio.renderers.default = "notebook_connected"
In [ ]:
# Path to the root directory of the dataset
ROOTDIR_DATASET_NORMAL = '../dataset/normal'
ROOTDIR_DATASET_ANOMALY = '../dataset/collisions'
# TF_ENABLE_ONEDNN_OPTS=0 means that the model will not use the oneDNN library for optimization
import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
Variours parameters¶
In [ ]:
#freq = '1.0'
#freq = '0.1'
#freq = '0.01'
freq = '0.005'
file_name_normal = "_20220811_rbtc_"
file_name_collisions = "_collision_20220811_rbtc_"
recording_normal = [0, 2, 3, 4]
recording_collisions = [1, 5]
freq_str = freq.replace(".", "_")
features_folder_normal = f"./features/normal{freq_str}/"
features_folder_collisions = f"./features/collisions{freq_str}/"
Data¶
In [ ]:
df_features_normal, df_normal_raw, _ = get_dataframes(ROOTDIR_DATASET_NORMAL, file_name_normal, recording_normal, freq, f"{features_folder_normal}")
df_features_collisions, df_collisions_raw, df_collisions_raw_action = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, recording_collisions, freq, f"{features_folder_collisions}1_5/")
df_features_collisions_1, df_collisions_raw_1, df_collisions_raw_action_1 = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, [1], freq, f"{features_folder_collisions}1/")
df_features_collisions_5, df_collisions_raw_5, df_collisions_raw_action_5 = get_dataframes(ROOTDIR_DATASET_ANOMALY, file_name_collisions, [5], freq, f"{features_folder_collisions}5/")
Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
Skipped feature extraction for pickFromPallet(1,2)=[true,1,0] 2022-08-11 14:37:37.436000 : 2022-08-11 14:37:37.421000. Skipped feature extraction for placeToPallet(1,1)=[true,0] 2022-08-11 14:37:37.421000 : 2022-08-11 14:37:37.442000. Skipped feature extraction for pickFromPallet(3,2)=[true,1,0] 2022-08-11 15:36:32.568000 : 2022-08-11 15:36:32.533000. Skipped feature extraction for pickFromPallet(3,2)=[true,1,0] 2022-08-11 15:36:32.572000 : 2022-08-11 15:36:32.561000. Skipped feature extraction for placeToPallet(1,3)=[true,0] 2022-08-11 15:36:32.533000 : 2022-08-11 15:36:32.572000. Skipped feature extraction for placeToPallet(1,3)=[true,0] 2022-08-11 15:36:32.561000 : 2022-08-11 15:36:32.561000. Features saved to ./features/normal0_005/features_statistical_200.0.csv. --- 106.68732285499573 seconds --- Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
Skipped feature extraction for moveOverPallet(1,3)=[true,0] 2022-08-11 16:55:15.149000 : 2022-08-11 16:55:15.146000. Skipped feature extraction for moveOverPallet(3,1)=[true,0] 2022-08-11 16:55:15.146000 : 2022-08-11 16:55:15.150000. Features saved to ./features/collisions0_005/1_5/features_statistical_200.0.csv. --- 38.67432403564453 seconds --- Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
Features saved to ./features/collisions0_005/1/features_statistical_200.0.csv. --- 22.279465198516846 seconds --- Loading data. Found 31 different actions. Loading data done. Computing features.
Progress: 0% Complete
Skipped feature extraction for moveOverPallet(1,3)=[true,0] 2022-08-11 16:55:15.149000 : 2022-08-11 16:55:15.146000. Skipped feature extraction for moveOverPallet(3,1)=[true,0] 2022-08-11 16:55:15.146000 : 2022-08-11 16:55:15.150000. Features saved to ./features/collisions0_005/5/features_statistical_200.0.csv. --- 19.869044065475464 seconds ---
In [ ]:
X_train, y_train, X_test, y_test, df_test = get_train_test_data(df_features_normal, df_features_collisions, full_normal=True)
X_train_1, y_train_1, X_test_1, y_test_1, df_test_1 = get_train_test_data(df_features_normal, df_features_collisions_1, full_normal=True)
X_train_5, y_train_5, X_test_5, y_test_5, df_test_5 = get_train_test_data(df_features_normal, df_features_collisions_5, full_normal=True)
Collisions¶
In [ ]:
collisions_rec1, collisions_init1 = get_collisions('1', ROOTDIR_DATASET_ANOMALY)
collisions_rec5, collisions_init5 = get_collisions('5', ROOTDIR_DATASET_ANOMALY)
# Merge the collisions of the two recordings in one dataframe
collisions_rec = pd.concat([collisions_rec1, collisions_rec5])
collisions_init = pd.concat([collisions_init1, collisions_init5])
In [ ]:
collisions_zones, y_collisions = get_collisions_zones_and_labels(collisions_rec, collisions_init, df_features_collisions)
collisions_zones_1, y_collisions_1 = get_collisions_zones_and_labels(collisions_rec1, collisions_init1, df_features_collisions_1)
collisions_zones_5, y_collisions_5 = get_collisions_zones_and_labels(collisions_rec5, collisions_init5, df_features_collisions_5)
RNN-EBM for Anomaly Detection in Time Series Data¶
In [ ]:
from algorithms.rnn_ebm import RecurrentEBM
# Disable eager execution
tf.compat.v1.disable_eager_execution()
classifier = RecurrentEBM(
num_epochs=100,
n_hidden=64,
n_hidden_recurrent=32,
min_lr=1e-4,
min_energy=None, # We'll set this to None initially and determine it after training
batch_size=128,
seed=42,
gpu=None # Set to None for CPU, or specify GPU index if available
)
# Train the RNN on normal data
classifier.fit(X_train)
print("RNN-EBM training completed.")
100%|██████████| 100/100 [00:10<00:00, 9.12it/s]
RNN-EBM training completed.
Predictions¶
In [ ]:
df_test = get_statistics(X_test, y_collisions, classifier, df_test, freq, threshold_type="mad")
df_test_1 = get_statistics(X_test_1, y_collisions_1, classifier, df_test_1, freq, threshold_type="mad")
df_test_5 = get_statistics(X_test_5, y_collisions_5, classifier, df_test_5, freq, threshold_type="mad")
Anomaly prediction completed.
Number of anomalies detected: 1 with threshold 16942358208.0, std
Number of anomalies detected: 112 with threshold 142.0788688659668, mad
Number of anomalies detected: 16 with threshold 632.2341003417969, percentile
Number of anomalies detected: 16 with threshold 612.8087134361267, IQR
Number of anomalies detected: 306 with threshold 0.0, zero
choosen threshold type: mad, with value: 142.0789
F1 Score: 0.8756
Accuracy: 0.9118
Precision: 0.8482
Recall: 0.9048
precision recall f1-score support
0 0.95 0.92 0.93 201
1 0.85 0.90 0.88 105
accuracy 0.91 306
macro avg 0.90 0.91 0.90 306
weighted avg 0.91 0.91 0.91 306
ROC AUC Score: 0.9304
Anomalies detected: 112
Best threshold: 120.1369 | F1 Score: 0.9067 | Precision: 0.8500 | Recall: 0.9714
Anomalies detected with best threshold: 120
-------------------------------------------------------------------------------------
Anomaly prediction completed.
Number of anomalies detected: 1 with threshold 23346397312.0, std
Number of anomalies detected: 43 with threshold 109.4520492553711, mad
Number of anomalies detected: 9 with threshold 527.282246398925, percentile
Number of anomalies detected: 23 with threshold 197.76518487930298, IQR
Number of anomalies detected: 164 with threshold 0.0, zero
choosen threshold type: mad, with value: 109.4520
F1 Score: 0.8462
Accuracy: 0.9268
Precision: 0.7674
Recall: 0.9429
precision recall f1-score support
0 0.98 0.92 0.95 129
1 0.77 0.94 0.85 35
accuracy 0.93 164
macro avg 0.88 0.93 0.90 164
weighted avg 0.94 0.93 0.93 164
ROC AUC Score: 0.9632
Anomalies detected: 43
Best threshold: 120.1369 | F1 Score: 0.8767 | Precision: 0.8421 | Recall: 0.9143
Anomalies detected with best threshold: 38
-------------------------------------------------------------------------------------
Anomaly prediction completed.
Number of anomalies detected: 10 with threshold 621.6637268066406, std
Number of anomalies detected: 10 with threshold 582.8217468261719, mad
Number of anomalies detected: 8 with threshold 679.8375244140625, percentile
Number of anomalies detected: 1 with threshold 742.22900390625, IQR
Number of anomalies detected: 141 with threshold 0.0, zero
choosen threshold type: mad, with value: 582.8217
F1 Score: 0.0303
Accuracy: 0.5461
Precision: 0.1000
Recall: 0.0179
precision recall f1-score support
0 0.58 0.89 0.70 85
1 0.10 0.02 0.03 56
accuracy 0.55 141
macro avg 0.34 0.46 0.37 141
weighted avg 0.39 0.55 0.44 141
ROC AUC Score: 0.8445
Anomalies detected: 10 Best threshold: 219.1636 | F1 Score: 0.8333 | Precision: 0.7237 | Recall: 0.9821 Anomalies detected with best threshold: 76 -------------------------------------------------------------------------------------
In [ ]:
plot_anomalies_true_and_predicted(df_collisions_raw, df_collisions_raw_action, collisions_zones, df_test, title="Collisions zones vs predicted zones for both recordings")